package javango.forms.fields;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

import javango.forms.widgets.TextInputWidget;
import javango.forms.widgets.WidgetFactory;

public class EmailField extends FieldBase {
	public final static String EMAILREGEXP = "[A-Z0-9._%-][+A-Z0-9._%-]*@(?:[A-Z0-9-]+\\.)+[A-Z]{2,4}$";
	
	@Inject
	public EmailField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		this.setWidget(TextInputWidget.class);
	}

	public Object clean(String value, Map<String, String> errors) {
		if (value == null) {
			errors.put(this.getName(), "Required");
		} else if (StringUtils.isEmpty(value)) {
			if (this.isRequired()) {
				errors.put(this.getName(), "Required");
			}
		} else if (!value.toUpperCase().matches(EMAILREGEXP)) {
			errors.put(this.getName(), "Not Valid Email");
		}
		return value;		
	}
	
}
